import Router from 'koa-router'
import multer, { MulterIncomingMessage } from 'koa-multer'
import path from 'path'
import fs from 'fs'
import _ from 'lodash'
const router = new Router()
const imgServiceUpload = multer({
  dest: '/home/upload/imgService',
  fileFilter: (req, file, callback) => {
    console.log(req, file)
    const type = 'png|jpeg|bmp|svg|jpg|gif'.includes(
      path.parse(file.originalname).ext.replace('.', '')
    )
    callback(null, type)
  },
  limits: {
    fileSize: 20 * 1024 * 1024
  }
}).single('uploadFile')

/**
 * 图床文件文件上传
 * 返还地址
 */
router.post('/imgServiceUploadFile', async (ctx, next) => {
  await imgServiceUpload(ctx, next)
    .then(() => {
      console.log((ctx.req as MulterIncomingMessage).file)
      const file = (ctx.req as MulterIncomingMessage).file
      if (_.isUndefined(file)) {
        ctx.body = { msg: '不接受此文件' }
        return
      }
      const { path: outPath, originalname, filename } = file
      const newPath = outPath + path.parse(originalname).ext // 获取原始文件后缀 加上当前文件名
      fs.renameSync(outPath, newPath)
      ctx.body = {
        msg:
          'https://mgaia.top/imgService/' +
          filename +
          path.parse(originalname).ext
      }
    })
    .catch((err: Error) => {
      console.log(err)
      ctx.body = { error: err.message }
    })
})

export default router
